<template>
  <div class="app-container">
    <div style="width:100%;height:30px;display: flex; justify-content: flex-end;">
      <el-button
          size="mini"
          type="primary" round
          @click="goToBack()"
      >返回上一页
      </el-button>
    </div>
    <div style="height: 10px"></div>
    <el-card shadow="never" :body-style="{ height: '10px' }" :style="{
      'margin-bottom': '10px','height': tableHeight
    }">
      <el-descriptions title="回款计划">
        <template slot="extra">
          <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
              v-hasPermi="['commission:plan:add']"
          >新增回款计划
          </el-button>
        </template>
      </el-descriptions>
      <el-table v-loading="loading" :data="planList" @selection-change="handleSelectionChange">
        <el-table-column label="批次名称" align="center" prop="planName"/>
        <el-table-column label="计划回款金额(元)" align="center" prop="planAmount"/>
        <el-table-column label="计划回款时间" align="center" prop="planDate" width="180">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.planDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="支付比例(%)" align="center" prop="rate"/>
        <el-table-column label="支付责任人" align="center" prop="responsiblePerson"/>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['commission:plan:edit']"
            >修改
            </el-button>
            <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
                style="color: red"
                v-hasPermi="['commission:plan:remove']"
            >删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <el-card shadow="never" :body-style="{ height: '10px' }" :style="{
      'margin-bottom': '10px','height': tableHeight
    }">
      <el-descriptions title="实际回款">
        <template slot="extra">
          <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleAddRel"
              v-hasPermi="['commission:real:add']"
          >新增实际回款
          </el-button>
        </template>
      </el-descriptions>
      <el-table v-loading="loading" :data="realList" @selection-change="handleSelectionChange">
        <el-table-column label="批次名称" align="center" prop="realName"/>
        <el-table-column label="实际支付金额(元)" align="center" prop="realAmount"/>
        <el-table-column label="实际支付时间" align="center" prop="realDate" width="180">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.realDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="支付比例(%)" align="center" prop="rate"/>
        <el-table-column label="支付责任人" align="center" prop="responsiblePerson"/>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdateRel(scope.row)"
                v-hasPermi="['commission:real:edit']"
            >修改
            </el-button>
            <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                style="color: red"
                @click="handleDeleteRel(scope.row)"
                v-hasPermi="['commission:real:remove']"
            >删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

    </el-card>

    <!-- 添加或修改保险合同佣金支付计划对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="900px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="批次名称" prop="planName">
          <el-input v-model="form.planName" placeholder="请输入批次名称"/>
        </el-form-item>
        <el-form-item label="计划回款金额" prop="planAmount">
          <el-input v-model="form.planAmount" placeholder="请输入计划回款金额">
            <template slot="append">
              <el-button slot="append">元</el-button>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="计划回款时间" prop="planDate">
          <el-date-picker clearable
                          v-model="form.planDate"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="请选择计划回款时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="支付比例" prop="rate">
          <el-input v-model="form.rate" placeholder="请输入支付比例">
            <template slot="append">
              <el-button slot="append">%</el-button>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="支付责任人" prop="responsiblePerson">
          <el-input v-model="form.responsiblePerson" placeholder="请输入支付责任人"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <commission-real :insureId="insureId" :contractId="contractId" ref="commissionReal1"></commission-real>
  </div>
</template>

<script>
import {listPlan, getPlan, delPlan, addPlan, updatePlan} from "@/api/commission/plan";
import {isEmpty, isValidAmount, isValidDecimal} from "@/utils/validate";
import {delReal, listReal} from "@/api/commission/real";
import commissionReal from '@/views/commission/real'

export default {
  name: "Plan",
  components: {
    commissionReal
  },
  data() {
    const checkPlanAmountRel = (rule, value, callback) => {
      if (isEmpty(value)) {
        callback();
        return
      }
      if (!isValidAmount(value)) {
        callback(new Error('请输入正确的金额'));
        return;
      }
      callback();
    }
    const checkRateRel = (rule, value, callback) => {
      if (isEmpty(value)) {
        callback();
        return
      }

      if (value > 100) {
        callback(new Error('回款比例不能大于100'));
        return;
      }
      if (value < 0) {
        callback(new Error('回款比例不能小于0'));
        return;
      }
      if (!isValidDecimal(value)) {
        callback(new Error('请输入正确的比例，小数不能超过2位'));
        return;
      }
      callback();
    }
    return {
      realList: [],
      tableHeight: 0,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 保险合同佣金支付计划表格数据
      planList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 9999,
        insureId: null,
        contractId: null,
        planName: null,
        planAmount: null,
        planDate: null,
        rate: null,
        responsiblePerson: null,
      },
      // 表单参数
      form: {},
      contractId: null,
      insureId: null,
      // 表单校验
      rules: {
        planAmount: [
          {validator: checkPlanAmountRel, trigger: 'blur'}
        ],
        rate: [
          {validator: checkRateRel, trigger: 'blur'}
        ]
      }
    };
  },
  mounted() {
    this.$nextTick(() => {
      let tableHeight = (window.innerHeight - 180) / 2
      this.tableHeight1 = tableHeight - 75
      this.tableHeight = tableHeight + 'px'
    })
  },
  created() {
    this.contractId = this.$route.query.contractId
    this.insureId = this.$route.query.insureId
    if (isEmpty(this.contractId) || isEmpty(this.insureId)) {
      this.$modal.msgWarning('缺少必要参数，请重新进入页面')
      return
    }
    this.getList();
  },
  methods: {
    goToBack() {
      this.$router.push({path: "/bxht/contract"});
    },
    handleDeleteRel(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除选中的保险合同佣金支付？').then(function () {
        return delReal(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    handleUpdateRel(row) {
      this.$refs.commissionReal1.openForm(row.id)
    },
    handleAddRel() {
      this.$refs.commissionReal1.openForm()
    },
    /** 查询保险合同佣金支付计划列表 */
    getList() {
      this.loading = true;
      this.queryParams.contractId = this.contractId
      this.queryParams.insureId = this.insureId
      listReal(this.queryParams).then(response => {
        this.realList = response.rows;
        // this.total = response.total;
        this.loading = false;
      });
      listPlan(this.queryParams).then(response => {
        this.planList = response.rows;
        // this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        insureId: null,
        contractId: null,
        planName: null,
        planAmount: null,
        planDate: null,
        rate: null,
        responsiblePerson: null,
        delFlag: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加保险合同佣金支付计划";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getPlan(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改保险合同佣金支付计划";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.contractId = this.contractId
          this.form.insureId = this.insureId
          if (this.form.id != null) {
            updatePlan(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addPlan(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除选中的保险合同佣金支付计划？').then(function () {
        return delPlan(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('commission/plan/export', {
        ...this.queryParams
      }, `plan_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
